package com.lcredu.minispring;

import com.lcredu.bean.Monster;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.InputStream;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 黎长容
 * @date 2025-07-12 11:58
 */
public class LcrApplicationContext {
    /**
     * 这个模拟spring容器里面的单例池存放bean的过程
     * 如果我的测试文件和编码文件在编译后同一个文件下就用下面这个可以获取
     * String path = this.getClass().getResource("/").getPath();
     * 如果不在,推荐使用流的方式进行获取
     * InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(xmlPath);
     */
    private ConcurrentHashMap<String, Object> singletonObjects = new ConcurrentHashMap<>();

    //接收存放bean的xml
    public LcrApplicationContext(String xmlPath) throws DocumentException, ClassNotFoundException, InstantiationException, IllegalAccessException {
        //拿到类路径
//        String path = this.getClass().getResource("/").getPath();
//        System.out.println(path);
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(xmlPath);

        //1.创建saxReader
        SAXReader reader = new SAXReader();

        //2.解析传递过来的xml文件,获取document对象
        Document document = reader.read(resourceAsStream);
        System.out.println("document=" + document);


        //3.获取根元素
        Element rootElement = document.getRootElement();

        //4.获取第一个bean
        Element bean = rootElement.elements("bean").get(0);

        String id = bean.attributeValue("id");
        String aClass = bean.attributeValue("class");

        List<Element> property = bean.elements("property");

        String monsterId = property.get(0).attributeValue("value");
        String name = property.get(1).attributeValue("value");
        String skill = property.get(2).attributeValue("value");

        //5.拿到它的属性之后,可以反射出对象
        Class<?> clazz = Class.forName(aClass);
        Monster monster = (Monster) clazz.newInstance();

        //6.可以进行反射赋值,但是这里我直接赋值
        monster.setMonsterId(new Integer(monsterId));
        monster.setName(name);
        monster.setSkill(skill);

        //7.最后放入singletonObjects中
        singletonObjects.put(id, monster);

    }

    public Object getBean(String monsterId) {
        return singletonObjects.get(monsterId);
    }
}
